import "dart:math";

import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/device/lock/api.dart";
import "package:ct_pa_majordomo/pages/widgets/menu_block.dart";
import "package:ct_pa_majordomo/utils/date_tools.dart";
import "package:ct_pa_majordomo/utils/index.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/bottom_sheet/index.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:ct_pa_majordomo/widgets/show_datetime_picker.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";

enum GetPwdKeyType {
  limit,
  permanent
}
class TabPane extends StatefulWidget {
  final int roomId;
  final GetPwdKeyType type;
  final List renter;
  const TabPane({super.key, required this.roomId, required this.type, required this.renter});

  @override
  State<StatefulWidget> createState() => _TabPaneState();

}

class _TabPaneState extends State<TabPane> {
  final DateTime currentDate = DateTime.now();
  List _selectList = [];
  List _lockList = [];
  final Map<String, dynamic> _params = {
    "account": null,
    "name": "",
    "startDate": DateTime.now(),
    "endDate": DateTime.now(),
    "remote": 1,
    "keyboardPwd": "",
  };

  void _getLocks() async {
    EasyLoading.show();
    Map resData = await lockApi.lockByRoomList(widget.roomId);
    EasyLoading.dismiss();
    setState(() {
      _lockList = resData["data"] ?? [];
    });
  }

  void _toggleLock(Map lockInfo) {
    setState(() {
      if (_selectList.contains(lockInfo["lockId"])) {
        _selectList.remove(lockInfo["lockId"]);
      } else {
        _selectList.add(lockInfo["lockId"]);
      }
    });
  }

  bool _canSend() {
    bool timePass = false;
    print("开始时间：${_params["startDate"] is DateTime}");
    var startDate = _params["startDate"] is DateTime ? _params["startDate"].millisecondsSinceEpoch : DateTime.parse(_params["endDate"]).millisecondsSinceEpoch;
    var endDate = _params["startDate"] is DateTime ? _params["endDate"].millisecondsSinceEpoch : DateTime.parse(_params["endDate"]).millisecondsSinceEpoch;

    if (startDate != endDate && endDate > startDate) {
      timePass = true;
    }

    if (widget.type == GetPwdKeyType.permanent) {
      if (_params["keyboardPwd"].isEmpty) {
        return false;
      } else if (_params["keyboardPwd"].length < 6 || _params["keyboardPwd"].length > 9) {
        return false;
      }
    }
    return Utils.isNotEmpty(_params["account"]) && Utils.isNotEmpty(_params["name"]) && timePass;
  }

  void _sendKey() async {
    Map<String, dynamic> data = {
      ..._params,
      "lockIds": _selectList.join(","),
      "startDate": DateTools.formatTime(_params["startDate"].millisecondsSinceEpoch),
      "endDate": DateTools.formatTime(_params["endDate"].millisecondsSinceEpoch),
      "keyboardPwd": GetPwdKeyType.limit == widget.type ? Random().nextInt(999999) + 100000 : _params["keyboardPwd"],
    };
    EasyLoading.show();
    await lockApi.sendPwds(data);
    EasyLoading.dismiss();
    EasyLoading.showToast("密码获取成功");
    Stacker.pop(true);
  }

  Future<void> _changeRenter() async {
    Map? popped = await showRoundedBottomSheet(
      builder: (context) => BottomSheetSelect(
        items: widget.renter,
        compare: (item) => item["renterId"] == _params["renterId"],
        itemAsString: (item) => item["name"],
      ),
    );
    if (popped != null) {
      setState(() {
        _params["renterId"] = popped["renterId"];
        _params["name"] = popped["name"];
        _params["account"] = popped["contacts"];
      });
    }
  }

  @override
  void initState() {
    super.initState();
    _getLocks();
  }

  @override
  Widget build(BuildContext context) {
    return ListView(
      padding: const EdgeInsets.all(ThemeVars.paddingPage),
      children: [
        MenuBlock(
          title: Text("选择锁"),
          items: List.generate(_lockList.length, (index) {
            Map item = _lockList[index];
            return MenuBlockItem(
                text: "",
                showArrow: false,
                onTap: () => _toggleLock(item),
                prefix: Row(
                  children: [
                    _selectList.contains(item["lockId"])
                        ? Icon(Icons.check_box_rounded, color: ThemeVars.colorPrimary, size: 20,)
                        : Icon(Icons.check_box_outline_blank_outlined, color: ThemeVars.colorTextTer, size: 20,),
                    SizedBox(width: 12,),
                    Text(item["lockName"]),
                  ],
                )
            );
          }),
        ),
        const SizedBox(height: 12,),
        MenuBlock(
            items: [
              MenuBlockItem(
                text: "姓名",
                suffix: Text(_params["name"]),
                onTap: () {
                  _changeRenter();
                }
              ),
              if (widget.type == GetPwdKeyType.permanent) MenuBlockItem(
                  text: "密码",
                  showArrow: false,
                  suffix: TextField(
                    textAlign: TextAlign.right,
                    decoration: const InputDecoration(
                      hintText: "请设置密码",
                      isDense: true,
                      counterText: "",
                    ),
                    maxLength: 9,
                    onChanged: (value) => setState(() {
                      _params["keyboardPwd"] = value;
                    }),
                  )
              ),
            ]
        ),
        const SizedBox(height: 12,),
        MenuBlock(
            items: [
              MenuBlockItem(
                text: "生效时间",
                showArrow: true,
                suffix: Text(
                  DateTools.formatTime(_params["startDate"].millisecondsSinceEpoch, format: "{y}-{m}-{d} {h}:{i}"),
                  style: const TextStyle(color: ThemeVars.colorTextTer),
                ),
                onTap: () {
                  showDatetimePicker(
                    context: context,
                    initialDateTime: _params["startDate"],
                    minimumDate: currentDate,
                    onchange: (value) => setState(() {
                      print(value);
                      if (value != null) _params["startDate"] = value;
                    }),
                  );
                },
              ),
              MenuBlockItem(
                text: "失效时间",
                showArrow: true,
                suffix: Text(
                  DateTools.formatTime(_params["endDate"].millisecondsSinceEpoch,
                      format: "{y}-{m}-{d} {h}:{i}"),
                  style: const TextStyle(color: ThemeVars.colorTextTer),
                ),
                onTap: () {
                  showDatetimePicker(
                    context: context,
                    initialDateTime: _params["endDate"],
                    minimumDate: currentDate,
                    onchange: (value) => setState(() {
                      if (value != null) _params["endDate"] = value;
                    }),
                  );
                },
              ),
            ]
        ),
        const SizedBox(height: 12,),
        Padding(
          padding: const EdgeInsets.only(top: 60,),
          child: Button(
            type: ButtonType.primary,
            onPressed: _canSend() ? () {
              print("下一步");
              _sendKey();
            } : null,
            child: const Text("发送"),
          ),
        )
      ],
    );
  }
}